package com.wyw.learning.thread.threadlocal;

/**
 * ThreadLocal的空指针问题
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * @date 2021/7/12   10:43 下午
 * <p>
 * Update History:
 * Author        Time            Content
 */
public class ThreadLocalNPE {
    ThreadLocal<Long> longThreadLocal = new ThreadLocal<>();

    public void set(){
        longThreadLocal.set(Thread.currentThread().getId());
    }

    public long get(){//如果改成Long包装类，那么就可以解决，但是基本类型long就会执行装箱拆箱，就会产生空指针异常
        return longThreadLocal.get();
    }

    public static void main(String[] args) {
        //主线程的情况
        ThreadLocalNPE threadLocalNPE = new ThreadLocalNPE();
//        threadLocalNPE.set();
//        System.out.println(threadLocalNPE.get());
        //子线程的情况
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
//                threadLocalNPE.set();//不设置初值，会直接返回null，这时候直接get会空指针
                System.out.println(threadLocalNPE.get());
            }
        });
        thread.start();
    }
}
